<template>
  <!-- form (竖屏) input -->
  <template v-if="inputStyle === 'v1'">
    <!-- 地图 -->
    <div v-if="formItem.sUIType === 'map' && scene === 'action'" id="map" style="width: 100%; height: 150px"></div>

    <van-field
      v-if="isShow"
      :type="type"
      :rows="rowNum"
      :disabled="disabled"
      v-model="itemValue"
      :maxlength="maxlength"
      :label="formItem.sTitle"
      :placeholder="placeholder"
      :required="required"
      :show-word-limit="showWordLimit"
      :error-message="errorMessage"
      @click="handleClick"
      @input="handleInput"
      @blur="handleBlur"
      @focus="handleFocus"
    >
      <template #input v-if="selectType.indexOf(formItem.sUIType) !== -1 || sFormat === 'star'|| sFormat === 'yearmonth;'">
        <!-- 上传 -->
        <template v-if="uploadType.indexOf(formItem.sUIType) !== -1">
          <van-uploader v-if="sFormat === 'refer:only-camera'" v-model="formValueList" multiple :after-read="handleUpload" :before-delete="deletePic" accept="image/*" capture="camera" :disabled="disabled">
            <template #preview-cover="{ file }">
              <div class="preview-cover van-ellipsis" @click.stop="handleDownload(file.name)">下载文件</div>
            </template>
          </van-uploader>

          <van-uploader v-else v-model="formValueList" multiple :after-read="handleUpload" accept="*" :disabled="disabled" :delete="deletePic">
            <template #preview-cover="{ file }">
              <div class="preview-cover van-ellipsis" @click.stop="handleDownload(file.name)">下载文件</div>
            </template>
          </van-uploader>
        </template>

        <!-- 评价 -->
        <template v-else-if="sFormat === 'star'">
          <van-rate v-model="numberItemValue" :size="24" color="#ffd21e" void-icon="star" void-color="#eee" />
        </template>

        <div v-else>
          <span v-if="itemValue" :style="{ color: disabled ? '#c9cacd' : '#323233' }">{{ itemValue }}</span>
          <span v-else style="color: #c9cacd">{{ placeholder }}</span>
        </div>
      </template>
      <template #right-icon>
        <div v-if="!disabled" style="display: flex; align-items: center; justify-content: flex-end">
          <van-icon name="clear" size="16" v-if="itemValue !== ''" @click.stop="handleClear" color="#C0C4CC" />
          <van-icon v-if="isShowArrow" size="14" name="arrow" />

          <!-- <van-icon v-if="formItem.sUIType === 'string' || formItem.sFormat !== ''" size="14" name="arrow" /> -->
        </div>
      </template>
      <template #button v-if="formItem.sUIType === 'map' && scene === 'action'">
        <van-button size="mini" type="primary" @click="configMap" plain>重新定位</van-button>
      </template>
    </van-field>
  </template>

  <!-- table (横屏) input -->
  <template v-else>
    <div class="vinput-box" :class="disabled ? 'disable-color' : ''" @click="handleClick">
      <span style="color: red; margin-right: 5px" v-if="required">*</span>
      <span v-if="isShowArrow">
        <span v-if="itemValue" :style="{ color: disabled ? '#c9cacd' : '#323233' }">{{ itemValue }}</span>
        <span v-else style="color: #c9cacd">{{ placeholder }}</span>
      </span>

      <input v-else style="pointer-events: auto" class="vinput" v-model="itemValue" :placeholder="placeholder" :disabled="disabled" @input="handleInput" />
      <van-icon name="arrow" color="#C0C4CC" v-if="isShowArrow" />
    </div>
  </template>

  <!-- 上传组件 -->
  <!-- <van-field v-else :label="formItem.sTitle" :required="required">
  </van-field> -->

  <!-- 参照弹窗 -->
  <van-popup teleport="#app" v-model:show="showeRefPopup" position="bottom" style="width: 100%; height: 90%" round>
    <template v-if="showeRefPopup">
      <OrgRef
        v-if="formItem.idJoinObject === 'dep' || formItem.idJoinObject === 'employee'"
        :refParams="refParams"
        :refObject="formItem.idJoinObject"
        :handleRefClick="handleRefClick"
        :handleRefCancle="handleRefCancle"
        :refMode="formItem.sUITypeExp"
      ></OrgRef>
      <Ref v-else :refParams="refParams" :refObject="formItem.idJoinObject" :handleRefClick="handleRefClick" :handleRefCancle="handleRefCancle" :refMode="formItem.sUITypeExp"></Ref>
    </template>
  </van-popup>

  <!-- 枚举弹窗 -->
  <van-popup teleport="#app" v-model:show="showeEnumPopup" position="bottom">
    <van-picker v-if="sUITypeExp === 'normal'" title="请选择" :columns="enumArr" @cancel="showeEnumPopup = false" @confirm="onConfirm" />

    <div v-else style="width: 100%; height: 50vh; padding: 20px">
      <div class="L-text L-text-align-center">请选择</div>
      <van-row :gutter="20" class="L-margin-top-20">
        <van-col :span="8" v-for="(item, index) in enumArr" :key="index">
          <div class="L-tag" :class="item.selected ? 'L-tag-selected' : ''" @click="item.selected = !item.selected">
            {{ item.text }}
          </div>
        </van-col>
      </van-row>

      <div class="L-bottom-row">
        <van-button round type="primary" style="width: 80%" @click="onMultipleEnumConfirm">确定</van-button>
      </div>
    </div>
  </van-popup>

  <!-- 日期弹窗 -->
  <van-popup teleport="#app" v-model:show="showDatePopup" position="bottom">
    <van-date-picker v-model="currentDateArr" title="选择日期" :columns-type="dataColumnsType" :min-date="minDate" :max-date="maxDate" @confirm="onConfirm" />
  </van-popup>

  <van-popup teleport="#app" v-model:show="showTimePopup" position="bottom">
    <van-time-picker v-model="currentTimeArr" title="选择时间" :columns-type="['hour', 'minute', 'second']" @confirm="onConfirm" />
  </van-popup>

  <!-- <van-popup v-model:show="showDatePopup" position="bottom">

    <van-date-picker v-model="currentDateArr" title="请选择" :columns-type="dataColumnsType" :min-date="minDate"
      :max-date="maxDate" @confirm="onConfirm" />
  </van-popup> -->

  <!--布尔弹窗 -->
  <van-popup teleport="#app" v-model:show="showeBoolPopup" position="bottom">
    <van-picker title="请选择" :columns="boolArr" @cancel="showeBoolPopup = false" @confirm="onConfirm" />
  </van-popup>

  <!-- 数字键盘 -->
  <van-number-keyboard
    teleport="#app"
    :show="showNumberKeyboard"
    :extra-key="showPoint ? '.' : ''"
    @blur="showNumberKeyboard = false"
    @input="handleClickNumberKeyBoard"
    @delete="handleClickNumberKeyBoardDelete"
    theme="custom"
    close-button-text="完成"
  />

  <!--refer弹窗  -->
  <!-- <van-action-sheet v-model:show="showReferSheet" :actions="referArr" @select="handleReferSelect"
    @cancel="showReferSheet = false" cancel-text="取消" /> -->

  <div v-if="showSelectLayer" class="L-input-select-layer" :style="{ top: pageTop }">
    <div class="L-select-layer-item" v-for="(item, index) in referArr" :key="index" @click="handleSelect(item)">
      <i class="iconfont icon-radio" style="margin-right: 5px"></i> <span>{{ item.rtitle }}</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import qs from 'qs'
import insterPointFuncObj from '@/function/insterPointFunc'
import { showLoadingToast, closeToast, showToast } from 'vant'
import type { FieldType, DatePickerColumnType, ActionSheetAction, PopoverAction } from 'vant'
import emitter from '@/utils/emitter'
import { defineProps, defineEmits, ref, onActivated, watch, provide, onMounted, watchEffect, computed } from 'vue'
import Ref from '../Ref/Ref.vue'
import OrgRef from '../Ref/OrgRef.vue'
import { apiConfigurable } from '@/request/api/api'

import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()

import { useRefStore } from '@/stores/ref'

const refStore = useRefStore()

const props = defineProps({
  formItem: {
    type: Object,
    default: null
  },
  disableControlField: {
    type: String,
    default: 'lCanInput'
  },
  scene: {
    type: String,
    default: 'form'
  },
  mapData: {
    type: Object,
    default: {
      lat: 39.907503,
      lng: 116.419936
    }
  },
  tableType: {
    type: String,
    default: 'head'
  },
  bodyDataName: {
    type: String,
    default: ''
  },
  bodyDataIndex: {
    type: String,
    default: ''
  },
  handleShowNumberKeyboardSpace: {
    type: Function,
    default: () => {}
  },

  jsondata: {
    type: Object,
    default: null
  },
  inputStyle: {
    type: String,
    default: 'v1'
  },
  handleSelectedSlor: {
    type: Function,
    default: () => {}
  }
})

const arrowType = ['ref', 'enum', 'datetime', 'date', 'bool','yearmonth']
const uploadType = ['picture', 'file']
const selectType = [...arrowType, ...uploadType]

const numberType = ['double', 'money', 'int']
const boolArr = [
  { text: '是', value: '是' },
  { text: '否', value: '否' }
]

const emits = defineEmits(['handleChange', 'getDistance', 'handleClear'])

const itemValue = ref<string | number>('')
const itemId = ref(props.formItem.valuehidden || '')
const formValueList = ref([]) //上传类型
const formValueId = ref('')
const fileList = ref([])
itemValue.value = props.formItem.value
const numberItemValue = computed({
  get() {
    return Number(itemValue.value)
  },
  set(newValue) {
    itemValue.value = String(newValue)
  }
})

if (uploadType.indexOf(props.formItem.sUIType) !== -1) {
  formValueList.value = props.formItem.valuelist
}

const errorMessage = ref<string>(props.formItem.errorMessage || '')

import { useEventFunc } from '@/function/eventFunc'
const eventFuncObj = useEventFunc()
watch(itemValue, (value) => {
  //错误信息
  if (value) {
    errorMessage.value = ''
  }
})

const disabled = ref(false)
const required = ref(false)
const isShow = ref(true)
const type = ref<FieldType>('text')
const rowNum = ref(1)
const maxlength = ref(500)
const enumArr = ref([])
const showWordLimit = ref(false)
const showPoint = ref(true)

const minDate = new Date(2012, 0, 1)
const maxDate = new Date(2030, 1, 31)

const showeRefPopup = ref(false)
watch(showeRefPopup, (value) => {
  if (!value) {
    refParams.value.inview = ''
  }
})
const showDatePopup = ref(false)
const showTimePopup = ref(false)
const showeEnumPopup = ref(false)
const showeBoolPopup = ref(false)
const showNumberKeyboard = ref(false)
const showReferSheet = ref(false)
const showReferPopover = ref(false)
const showSelectLayer = ref(false)

const refParams = ref({
  object: props.formItem.idJoinObject,
  toobject: props.formItem.idObject,
  field: props.formItem.sField,
  sRefKey: props.formItem.sRefKey,
  classname: props.formItem.classname,
  sFieldRef: props.formItem.sFieldRef,
  params: '',
  inview: ''
})

//是否可编辑的控制字段判断
// const disableControlField = props.disableControlField
if (props.disableControlField === 'lCanInput') {
  disabled.value = props.formItem.lCanInput === '0' ? true : false
} else if (props.disableControlField === 'sEditable') {
  disabled.value = props.formItem.sEditable === 'false' ? true : false
}

const placeholder = ref('')
placeholder.value = disabled.value ? "系统自动填充" : "请输入" + props.formItem.sTitle;
// placeholder.value = '请输入'

if (props.formItem.lMustInput) {
  required.value = props.formItem.lMustInput === '0' ? false : true
}
if (props.formItem.lCanOutput) {
  isShow.value = props.formItem.lCanOutput === '0' ? false : true
}

const sUITypeExp = props.formItem.sUITypeExp
const sUIType = props.formItem.sUIType
const sFormat = props.formItem.sFormat
const currentDateArr = ref<string[]>([])
const currentTimeArr = ref<string[]>([])

const dataColumnsType = ref<DatePickerColumnType[]>(['year', 'month', 'day'])
// const referArr = ref<ActionSheetAction[]>([])
const referArr = ref<PopoverAction[]>([])

const isShowArrow = computed(() => {
  if (selectType.indexOf(sUIType) !== -1 || sFormat === 'yearmonth;') {
    return true
  }
})

//type
switch (sUIType) {
  case 'string':
    type.value = sUITypeExp == 'long' || sUITypeExp == 'big' ? 'textarea' : 'text'
    showWordLimit.value = type.value === 'textarea' ? true : false
    rowNum.value = sUITypeExp == 'long' || sUITypeExp == 'big' ? 2 : 1
    maxlength.value = parseInt(props.formItem.lLength || 500)
    break

  case 'int':
    type.value = 'digit'
    break

  case 'double':
    type.value = 'number'
    break

  case 'url':
    if (sUITypeExp === 'mobilephone') {
      type.value = 'tel'
    }
    break

  case 'datetime':
    const now = itemValue.value == '' ? getCurrentTime(sUITypeExp, '') : itemValue.value

    if (sUITypeExp === 'short') {
      currentDateArr.value = now.split('-')
      currentTimeArr.value = now.split(':')
    } else {
      currentDateArr.value = now.split(' ')[0].split('-')
      currentTimeArr.value = now.split(' ')[1].split(':')
    }

    break

  case 'map':
    type.value = 'textarea'
    rowNum.value = 3
    break
}

showPoint.value = props.formItem.sUIType == 'int' ? false : true
let timer = null

const deletePic = (v) => {
  const index = formValueList.value.findIndex(i => {
    return i.url == v.url
  })
  formValueList.value.splice(index,1)
  let newId = itemId.value.split(';')
  newId.splice(index,1)
  let newValue = itemValue.value.split(';')
  newValue.splice(index,1)
  itemValue.value = newValue.join(';')
  itemId.value = newId.join(';')
  console.log(itemValue.value,itemId.value,formValueList.value,2121)
}
function handleInput(e) {
  // 事件函数处理
  const { event } = props.formItem
  const { jsondata, tableType, bodyDataIndex, bodyDataName } = props
  if (event && Array.isArray(event)) {
    if (event.length > 0) {
      event.forEach((item, index) => {
        // if (item.eventSource.includes('hhys')) {
        // eventFuncObj.parseEventSource('hhys', jsondata, tableType, bodyDataIndex, bodyDataName)
        // } else {
        eventFuncObj.parseEventSource(item.eventSource, jsondata, tableType, bodyDataIndex, bodyDataName)
        // }
      })
    }
  }

  //业务特判===========================
  if (!timer) {
    timer = setTimeout(() => {
      timer = null
      handleSearchAccount()
    }, 1000)
  }
}
onMounted(() => {
  const { value,sField } = props.formItem
  if (value && sField == 'quantity') {
    handleInput(value)

  }
})
function handleClick(e) {
  if (disabled.value === true) {
    return
  }

  pageTop.value = e.pageY
  showSelectLayer.value = false

  // 插入点函数
  const jsfunc = props.formItem?.jsfunc
  const idObject = props.formItem.idObject
  if (jsfunc && insterPointFuncObj[jsfunc.slice(0, -2)]) {
    const insterPointFuncRes = insterPointFuncObj[jsfunc.slice(0, -2)](props.jsondata, idObject)
    if (!insterPointFuncRes) {
      return
    } else {
      refParams.value.params = insterPointFuncRes
    }
  }

  const { formItem, tableType, jsondata, bodyDataName, bodyDataIndex } = props

  //字符串
  if (sUIType === 'string' || sUIType === 'yearmonth' ) {
    if (sFormat === 'yearmonth;') {
      dataColumnsType.value = ['year', 'month']
      const nowtime = itemValue.value == '' ? getCurrentTime('', 'yearmonth') : itemValue.value
      currentDateArr.value = nowtime.split('-')
      showDatePopup.value = true
    }

    if (sFormat.indexOf('refer') !== -1) {
      const content = getContentBetween(sFormat, 'refer:', ';')
      referArr.value = content.split(',').map((item: string) => {
        return { rtitle: item }
      })

      showSelectLayer.value = true
    }
  }

  // 枚举
  if (sUIType === 'enum') {
    showeEnumPopup.value = true
    const enumIdArr = props.formItem.allenumid.split(';').filter((item) => item)

    enumArr.value = props.formItem.allenumval
      .split(';')
      .filter((item) => item)
      .map((item, index) => {
        return { text: item, value: item, id: enumIdArr[index] }
      })
  }

  // 日期时间
  if (sUIType === 'datetime') {
    showDatePopup.value = true
  }

  // 日期时间
  if (sUIType === 'date') {
    showDatePopup.value = true
  }

  // 参照
  if (sUIType === 'ref') {
    // 字段约束
    let inview = formItem.inview
    if (inview) {
      let arrinview = inview.split(';')
              console.log(1,arrinview)

      for (let inviewindex in arrinview) {
        console.log(2,inviewindex)
        let arrinviewdata = arrinview[inviewindex]
        let inviewdatas = arrinviewdata.split(':')
        if (inviewdatas[1] === 'eq') {

          if (tableType === 'head') {
            for (let groupindex in jsondata.head) {
              for (let itemindex in jsondata.head[groupindex].groupvalue) {
                let item = jsondata.head[groupindex].groupvalue[itemindex]
                if (item.sField === inviewdatas[2].split('_')[2]) {
                  refParams.value.inview += inviewdatas[0] + ':eqref:' + item.valuehidden + ';'
                  // refParams.value.inview += inviewdatas[0] + `:${item.sFieldRef == 'sname'? 'eq' : 'eqref'}:` + item.valuehidden + ';'
                }
              }
            }
          } else if (tableType === 'body') {
            for (let itemindex in jsondata.bodydata[bodyDataName][bodyDataIndex]) {
              let item = jsondata.bodydata[bodyDataName][bodyDataIndex][itemindex]
              if (item.sField === inviewdatas[0]) {
                refParams.value.inview += inviewdatas[0] + ':eqref:' + item.valuehidden + ';'
              }
            }
          }
        } else if (inviewdatas[0] === 'sname' && inviewdatas[1] === 'in') {
          refParams.value.inview += `${inviewdatas[0]}:${inviewdatas[1]};`
        } else if (inviewdatas[1] === 'in') {
          refParams.value.inview += inviewdatas[0] + ':in:' + formItem.value + ';'
        }
      }
    }

    showeRefPopup.value = true
  }

  //布尔
  if (sUIType === 'bool') {
    showeBoolPopup.value = true
  }

  //数字
  if (numberType.indexOf(formItem.sUIType) !== -1) {
    // showNumberKeyboard.value = true;
  }
}

function handleBlur() {
  // showSelectLayer.value = false
}

function handleFocus(e) {}

function handleSelect(item) {
  itemValue.value = item.rtitle
  showSelectLayer.value = false

  // 业务特判
  const { idObject, sField, value } = props.formItem
  if ((idObject === 'account' || idObject === 'account1' || idObject === 'account2') && sField == 'sname') {
    props.handleSelectedSlor(item)
  }
}

const accountArr = ref([])

function handleSearchAccount() {
  const { idObject, sField, value } = props.formItem
  if ((idObject === 'account' || idObject === 'account1' || idObject === 'account2') && sField == 'sname') {
    showLoadingToast({
      duration: 0, // 持续展示 toast
      forbidClick: true,
      message: '查询中...'
    })

    const api = `${idObject}.querysolr.do`
    const data = {
      sname: value
    }

    showSelectLayer.value = false

    // 本地静态代码==========================
    // const arr = [
    //   {
    //     creditcode: "-",
    //     cws: "",
    //     hospgrade: "2c9a2d9293e37a9f0193f166f5fa0293",
    //     hospgradeEnum: "未评级",
    //     id: "16209786644060683491497060319379",
    //     idquxian: "BCEDCB1DE2B84B4B87FD6356476918E2",
    //     idsheng: "014341AC530B4C5D9EB0C7AC21C32BAD",
    //     idshi: "42B24642489F485ABF67D530C09EEF01",
    //     jd: "110.094489",
    //     khsx: "2c9a2d9270e26d770170ec1797af04bd",
    //     khsxEnum: "基层医疗",
    //     quxianRef: "福绵区",
    //     regstatus: "-",
    //     rmzl: "",
    //     saddress: "福绵区新桥镇被霞村村委左侧",
    //     score: 11.047103,
    //     shengRef: "广西壮族自治区",
    //     shiRef: "玉林市",
    //     sjcustomer: "",
    //     sjcustomerRef: "",
    //     sname: "玉林市福绵区新桥镇被霞村卫生室",
    //     snameAllname: "玉林市福绵区新桥镇被霞村卫生室",
    //     swebsite: "",
    //     wd: "22.502364",
    //     yylx: "",
    //   },

    //   {
    //     creditcode: "-",
    //     cws: "",
    //     hospgrade: "2c9a2d9293e37a9f0193f166f5fa0293",
    //     hospgradeEnum: "未评级",
    //     id: "16209786644060683491497060319379",
    //     idquxian: "BCEDCB1DE2B84B4B87FD6356476918E2",
    //     idsheng: "014341AC530B4C5D9EB0C7AC21C32BAD",
    //     idshi: "42B24642489F485ABF67D530C09EEF01",
    //     jd: "110.094489",
    //     khsx: "2c9a2d9270e26d770170ec1797af04bd",
    //     khsxEnum: "基层医疗",
    //     quxianRef: "福绵区",
    //     regstatus: "-",
    //     rmzl: "",
    //     saddress: "北京市昌平区小汤山镇",
    //     score: 11.047103,
    //     shengRef: "广西壮族自治区",
    //     shiRef: "玉林市",
    //     sjcustomer: "",
    //     sjcustomerRef: "",
    //     sname: "北京小汤山医院（北京小汤山疗养院、北京市小汤山康复医院、北京国际药膳博物馆北京市健康管理促进中心）",
    //     snameAllname: "北京小汤山医院（北京小汤山疗养院、北京市小汤山康复医院、北京国际药膳博物馆北京市健康管理促进中心） 北京小汤山医院（北京小汤山疗养院北京市小汤山康复医院北京国际药膳博物馆北京市健康管理促进中心） 北京小汤山医院（北京小汤山疗养院、北京市小汤山康复医院、北京国际药膳博物馆） 北京小汤山医院（北京小汤山疗养院、北京市小汤山康复医院、北京国际药膳博 北京小汤山医院 北京小汤山疗养院 北京小汤山康复医院",
    //     swebsite: "http://www.xtshos.com.cn",
    //     wd: "22.502364",
    //     yylx: "",
    //   },
    // ]

    // referArr.value = arr.map(item => {
    //   return { text: item.sname, ...item }
    // })
    // showSelectLayer.value = true

    // closeToast()
    // ====================================

    apiConfigurable(api, data).then((res) => {
      if (res.code === 0) {
        if (res.data.jsondata !== 'null') {
          referArr.value = res.data.jsondata.map((item) => {
            return { rtitle: item.sname, ...item }
          })
          showSelectLayer.value = true
        }
        closeToast()
      }
    })
  }
}

const pageTop = ref(0)

function getCurrentTime(type: string = '', format: string = '') {
  const currentTime = new Date()
  const year = currentTime.getFullYear()
  const month = currentTime.getMonth() + 1 // 月份从0开始，因此需要加1
  const day = currentTime.getDate()
  const hours = currentTime.getHours()
  const minutes = currentTime.getMinutes()
  const seconds = currentTime.getSeconds()
  if (type) {
    return type === 'short' ? `${year}-${month}-${day}` : `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
  if (format) {
    if (format === 'yearmonth') return `${year}-${month}`
  }
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

function getContentBetween(str, startChar, endChar) {
  const regex = new RegExp(`${startChar}([^${endChar}]+)${endChar}`)
  const match = str.match(regex)
  return match ? match[1] : '' // 返回匹配的内容，如果没有找到，返回空字符串
}

// function onConfirm({ selectedValues }) {
let timeFlag = ref(false)
function onConfirm({ selectedOptions, selectedValues }) {
  // console.log("&&&&", selectedOptions, selectedValues);

  // 字符串
  if ((sUIType === 'string' || sUIType === 'yearmonth') && sFormat === 'yearmonth;') {
    itemValue.value = selectedValues.join('-')
    currentDateArr.value = selectedValues
    showDatePopup.value = false
  }

  //枚举类型
  if (sUIType === 'enum') {
    itemValue.value = selectedValues[0]
    itemId.value = selectedOptions[0].id
    showeEnumPopup.value = false
  }

  //日期类型
  if (sUIType === 'datetime') {
    showDatePopup.value = false
    // console.log("*****", timeFlag.value);
    if (sUITypeExp === 'short') {
      itemValue.value = selectedValues.join('-')
    } else {
      if (timeFlag.value === false) {
        itemValue.value = selectedValues.join('-')
        showTimePopup.value = true
        timeFlag.value = true
      } else {
        itemValue.value = `${itemValue.value} ${selectedValues.join(':')}`
        showTimePopup.value = false
        timeFlag.value = false
      }
    }
  }

  if (sUIType === 'date') {
    showDatePopup.value = false
    itemValue.value = selectedValues.join('-')
  }

  //布尔类型
  if (sUIType === 'bool') {
    itemValue.value = selectedValues[0]
    showeBoolPopup.value = false
  }
}

function onMultipleEnumConfirm() {
  itemValue.value = enumArr.value.reduce((pre, item) => {
    if (item.selected === true) {
      return `${pre}${item.text};`
    } else {
      return pre
    }
  }, '')

  itemId.value = enumArr.value.reduce((pre, item) => {
    if (item.selected === true) {
      return `${pre}${item.id};`
    } else {
      return pre
    }
  }, '')

  showeEnumPopup.value = false
}

interface refParams {
  id: string
  title: string
  address?: string
  fieldmap?: object
  mapobject?: string
}

const fieldmap = ref({}) //映射关心
const mapobject = ref('') //映射对象

function handleRefClick(item: refParams) {
  itemValue.value = item.title
  itemId.value = item.id
  if (item.fieldmap && item.mapobject) {
    fieldmap.value = item.fieldmap
    mapobject.value = item.mapobject
  }
  // 事件函数处理
  const { event } = props.formItem
  const { jsondata, tableType, bodyDataIndex, bodyDataName } = props
  if (event && Array.isArray(event)) {
    if (event.length > 0) {
      event.forEach((item, index) => {
        eventFuncObj.parseEventSource(item.eventSource, jsondata, tableType, bodyDataIndex, bodyDataName)
      })
    }
  }

  showeRefPopup.value = false
}

function handleRefCancle() {
  showeRefPopup.value = false
}

//upload======================
const oldNameStr = ref('')
const newNameStr = ref('')
function handleUpload(file) {
  let deviceFile = []
  let formData = new FormData()
  if (Array.isArray(file)) {
    deviceFile = file
  } else {
    deviceFile.push(file)
  }

  for (let i = 0; i < deviceFile.length; i++) {
    formData.append('file' + i, deviceFile[i].file, deviceFile[i].name)
  }
  showLoadingToast({
    duration: 0, // 持续展示 toast
    forbidClick: true,
    message: '上传中...'
  })

  const { sUIType } = props.formItem

  const api = sUIType === 'picture' ? 'upload.imagedo' : 'upload.filedo'

  apiConfigurable(api, formData).then((res) => {
    if (res.code === 0) {
      closeToast()
      itemValue.value += res.data[0].oldname + ';'
      itemId.value +=  res.data[0].newname + ';'

      oldNameStr.value += res.data[0].oldname + ';'
      newNameStr.value += res.data[0].newname + ';'
    }
  })
}

function handleDownload(filename) {
  const index = oldNameStr.value.split(';').indexOf(filename)
  const newname = newNameStr.value.split(';')[index]

  if (newname) {
    const url = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '/')
    window.location.href = `${url}/userfile/default/attach/${newname}`
  }
}

function handleClickNumberKeyBoard(value) {
  itemValue.value = `${itemValue.value}${value}`
}

function handleClickNumberKeyBoardDelete() {
  itemValue.value = itemValue.value.slice(0, -1)
}

function handleClear() {
  emits('handleClear', props.formItem, props.jsondata, props.tableType)
}

watch(showNumberKeyboard, (val) => {
  props.handleShowNumberKeyboardSpace(val)
})

// 监听数据变化
watch(
  itemValue,
  () => {
    emits('handleChange', props.formItem, itemValue.value, itemId.value, fieldmap.value, mapobject.value, props.tableType, props.bodyDataName, props.bodyDataIndex)
  },
  {
    immediate: true
  }
)
// 监听数据变化
watch(
  itemId,
  () => {
    emits('handleChange', props.formItem, itemValue.value, itemId.value, fieldmap.value, mapobject.value, props.tableType, props.bodyDataName, props.bodyDataIndex)
  },
    {
    immediate: true
  }
)

//字段映射监听
watch(
  () => props.formItem.value,
  (value) => {
    itemValue.value = value
  }
)
//字段映射监听
watch(
  () => props.formItem.valuehidden,
  (value) => {
    itemId.value = value
  }
)

//字段联动监听
watch(
  () => props.formItem.lCanInput,
  (value) => {
    disabled.value = props.formItem.lCanInput === '0' ? true : false
  }
)

watch(
  () => props.formItem.lMustInput,
  (value) => {
    required.value = props.formItem.lMustInput === '0' ? false : true
  }
)

watch(
  () => props.formItem.lCanOutput,
  (value) => {
    isShow.value = props.formItem.lCanOutput === '0' ? false : true
  }
)

//地图===========================================================
import wx from 'weixin-js-sdk'
import * as dd from 'dingtalk-jsapi'
import AMapLoader from '@amap/amap-jsapi-loader'

onMounted(() => {
  if (props.formItem.sUIType === 'map' && props.scene === 'action') {
    configMap()
  }
})

const map = ref({})
const ua = ref('') //
const logintype = ref('')
const clttype = ref('')
const tourl = ref('')
const AMapObj = ref({}) //高德地图实例

const center = ref<number[] | string[]>([0, 0])

const gaodeLocationStatus = ref('init')
const otherLocationStatus = ref('init')

const geoCoder = ref({})

//配置地图
function configMap() {
  AMapLoader.load({
    key: 'e762e8d8003a79d26ece5f84b4afbfb0', // 高德地图API Key
    version: '2.0', // 指定API版本
    plugins: ['AMap.Geolocation', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.Geocoder'] // 需要使用的插件
  })
    .then((AMap) => {
      AMapObj.value = AMap //保存高德实例

      initMap()
      getEnvironment() //获取当前运行环境(钉钉or微信)

      // 配置高德通过经纬度获取地址
      geoCoder.value = new AMap.Geocoder({
        batch: true,
        radius: 200,
        extensions: 'all'
      })

      // 配置高德定位
      const gaolocation = new AMap.Geolocation({
        enableHighAccuracy: true,
        timeout: 7000,
        zoomEnable: false,
        dragEnable: false,
        showButton: false,
        buttonOffset: new AMap.Pixel(10, 20),
        zoomToAccuracy: false
      })

      showLoadingToast({
        message: '加载中...',
        forbidClick: true,
        duration: 0
      })

      gaodeLocationStatus.value = 'init'

      gaolocation.getCurrentPosition(function (status, result) {
        if (status === 'complete') {
          // console.log("高德获取的位置信息*******", result, [
          //   result.position.lng,
          //   result.position.lat,
          // ]);
          gaodeLocationStatus.value = 'success'

          // itemValue.value = `${result.formattedAddress} && ${center.value[0]},${center.value[1]}`;

          center.value[0] = result.position.lng
          center.value[1] = result.position.lat
          initMap()
          emits('getDistance', center)
          getAddress()
          closeToast()
        } else {
          // console.log("高德定位失败&&&&&&&&", result);
          emits('getDistance', [116.42, 39.91])
          closeToast()
        }
      })
      return
    })
    .catch((e) => {
      console.log('高德地图配置错误', e)
    })
}

//初始化高德地图
function initMap() {
  const AMap = AMapObj.value
  map.value = new AMap.Map('map', {
    zoom: 15, // 初始缩放级别
    center: center.value // 初始中心点坐标
  })

  const position = new AMap.LngLat(center.value[0], center.value[1])
  var marker = new AMap.Marker({
    position: position,
    offset: new AMap.Pixel(-0, -0)
  })

  map.value.add(marker)
}

//获取地理位置
function getEnvironment() {
  ua.value = window.navigator.userAgent.toLowerCase()
  logintype.value = 'wechat'
  tourl.value = window.location.href
  clttype.value = 'android'
  if (ua.value.indexOf('iphone') !== -1) {
    clttype.value = 'ios'
  }

  if (ua.value.indexOf('wxwork') !== -1) {
    logintype.value = 'wxwork'
    // weixinConfigure();
    getSignature()
  } else if (ua.value.indexOf('dingtalk') !== -1) {
    logintype.value = 'dingding'
    getSignature()
  } else if (ua.value.indexOf('micromessenger') !== -1) {
    logintype.value = 'wechat'
    // weixinConfigure();
    getSignature()
  } else {
    logintype.value = 'browser'
  }
}

//获取签名(微信和钉钉)
function getSignature() {
  let data = {
    url: tourl.value,
    type: logintype.value,
    clttype: clttype.value
  }

  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0
  })

  const { idobject } = route.query
  let url = idobject + '.getlocation.do'
  apiConfigurable(url, qs.stringify(data)).then((res) => {
    if (res.code === 0) {
      let data = res.data

      if (logintype.value === 'weixin') {
        wexinLocaltion(data)
      }

      if (logintype.value === 'dingding') {
        ddLocation(data)
      }
    }
  })
}

function wexinLocaltion(data) {
  wx.config({
    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
    appId: data.appId, // 必填，公众号的唯一标识
    timestamp: data.timestamp, // 必填，生成签名的时间戳
    nonceStr: data.nonceStr, // 必填，生成签名的随机串
    signature: data.signature, // 必填，签名
    jsApiList: ['getLocation'] // 必填，需要使用的JS接口列表
  })
  wx.ready(function () {
    wx.getLocation({
      type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
      success: function (res) {
        if (gaodeLocationStatus.value === 'success') return
        otherLocationStatus.value = 'success'
        center.value[0] = res.longitude
        center.value[1] = res.latitude
        emits('getDistance', center)
        getAddress()
        closeToast()
      }
    })
  })
}

function ddLocation(data) {
  let configData = {
    agentId: data.agentid,
    corpId: data.appId,
    timeStamp: data.timestamp,
    nonceStr: data.nonceStr,
    signature: data.signature,
    type: 0,
    jsApiList: [
      'biz.contact.choose',
      'chooseChat',
      // "runtime.info",
      // "biz.contact.choose",
      // "device.notification.confirm",
      // "device.notification.alert",
      // "device.notification.prompt",
      // "biz.ding.post",
      // "biz.util.openLink",
      'device.geolocation.get'
    ]
  }
  dd.config(configData)
  dd.error(function (error) {
    console.log('dingding' + error)
  })
  dd.ready(function () {
    dd.device.geolocation.get({
      targetAccuracy: 200,
      coordinate: 1,
      withReGeocode: false,
      useCache: true,
      onSuccess: function (res) {
        if (gaodeLocationStatus.value === 'success') return
        otherLocationStatus.value = 'success'
        center.value[0] = res.longitude
        center.value[1] = res.latitude
        emits('getDistance', center)
        getAddress()
        closeToast()
      },
      onfail: function (err) {
        emits('getDistance', [116.42, 39.91])
        otherLocationStatus.value = 'fail'
        if (otherLocationStatus.value === 'fail') {
          showToast(`钉钉定位失败,请检查是否开启位置权限`)
        }
        setTimeout(() => {
          closeToast()
        }, 1000)
      }
    })
  })
}

function getAddress() {
  geoCoder.value.getAddress(center.value, function (status, result) {
    if (status === 'complete' && result.info === 'OK') {
      if (gaodeLocationStatus.value === 'success') {
        const address = result.regeocode.formattedAddress || ''
        itemValue.value = `${address}&&${center.value[0]},${center.value[1]}`
      } else {
        const address = result.regeocode.formattedAddress || ''
        itemValue.value = `${address}&${center.value[0]},${center.value[1]}`
      }

      initMap()
    }
  })

  return
}

// 本地测试账号====================================================
import { getAccessToken, getJsApiTicket } from '@/utils/wexin.js'

function weixinConfigure() {
  if (!sessionStorage.getItem('access_token')) {
    getAccessToken(weixinConfigure)
  } else {
    if (!sessionStorage.getItem('js_ticket')) {
      getJsApiTicket(sessionStorage.getItem('access_token'), weixinConfigure)
    }

    const url = window.location.href
    const noncestr = 'levy110222'
    const jsapi_ticket = sessionStorage.getItem('js_ticket')
    const timestamp = new Date().getTime()

    const str = `jsapi_ticket=${jsapi_ticket}&noncestr=${noncestr}&timestamp=${timestamp}&url=${url}`

    var hash = CryptoJS.SHA1(str)
    const signature = hash.toString(CryptoJS.enc.Hex)
    wx.config({
      debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
      appId: 'wx09830bf23f70b003', // 必填，公众号的唯一标识
      timestamp, // 必填，生成签名的时间戳
      nonceStr: noncestr, // 必填，生成签名的随机串
      signature, // 必填，签名
      jsApiList: ['getLocation'] // 必填，需要使用的JS接口列表
    })
    wx.ready(function () {
      wx.getLocation({
        // type: "wgs84", // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
        type: 'gcj02',
        success: function (res) {
          // const latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
          // const longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
          // const speed = res.speed; // 速度，以米/每秒计
          // const accuracy = res.accuracy; // 位置精度
          center.value[0] = res.longitude
          center.value[1] = res.latitude
          getAddress()
        }
      })
    })
  }
}
</script>

<style>
.L-input-select-layer {
  width: 80vw;
  position: absolute;
  z-index: 9999;
  background-color: #fff;
  border-radius: 6px;
  padding: 10px;
  box-sizing: border-box;
  left: 10vw;
  box-shadow: 0 2px 12px rgba(50, 50, 51, 0.12);
  max-height: 200px;
  overflow: scroll;
}

.L-select-layer-item {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #f9f9f9;
  padding: 10px 0;
}

.L-tag {
  width: 100%;
  /* max-width: 70px; */
  /* min-width: 40px; */

  text-align: center;
  padding: 2px 5px;
  background: #f5f7fa;
  border-radius: 4px;
  color: #606266;
  font-size: 12px;
  margin: 0px 5px 10px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.L-tag-selected {
  background: #1989fa;
  color: #fff;
}

.van-field__body {
  display: flex;
  align-items: flex-end;
}

.vinput-box {
  border-radius: 4px;
  padding: 2px 4px;
  border: 1px solid #e4e7ed;
  display: flex;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.disable-color {
  background-color: #eff0f2;
}

.vinput {
  all: unset;
  /* border:none; */
  width: 90%;
  /* border:1px solid #EBEEF5;
  padding:2px 5px;
  border-radius: 4px; */
  user-select: auto;
}

.vinput::placeholder {
  color: #c0c4cc !important;
}

input[disabled],
input:disabled,
input.disabled,
.van-field__control:disabled {
  color: #c0c4cc !important;
  -webkit-text-fill-color: #c0c4cc !important;
  -webkit-opacity: 1 !important;
  opacity: 1 !important;
}

.van-popover__wrapper {
  display: block;
}

.preview-cover {
  position: absolute;
  bottom: 0;
  box-sizing: border-box;
  width: 100%;
  padding: 4px;
  color: #fff;
  font-size: 12px;
  text-align: center;
  background: rgba(0, 0, 0, 0.6);
}
</style>
